﻿using Common.LoadBalancer.Abstractions;
using Common.ServiceDiscovery.Model;

namespace Common.LoadBalancer.Selectors
{
    public class RoundRobinSelector : ILoadBalancer
    {
        private readonly Func<Task<IList<ServiceInformation>>> _services;
        private readonly string _serviceName;
        private int _last;
        private static readonly object _syncLock = new object();
        public RoundRobinSelector(Func<Task<IList<ServiceInformation>>> services, string serviceName)
        {
            _services = services;
            _serviceName = serviceName;
        }

        public async Task<HostAndPort> Lease()
        {
            var services = await _services.Invoke() ?? new List<ServiceInformation>();

            if (services == null || services.Count == 0)
                throw new Exception($"{_serviceName}没有找到实例");

            lock (_syncLock)
            {
                Interlocked.Increment(ref _last);

                if (_last >= services.Count)
                {
                    Interlocked.Exchange(ref _last, 0);
                }

                return services[_last].HostAndPort;
            }

        }

        public void Release(HostAndPort hostAndPort)
        {
        }
    }
}
